#include "tgaimage.h"
#include "rasterizer.h"
#include "myEigen.h"

#include <iostream>
#include <chrono>
#include <filesystem>
#include <vector>
#include <memory>

using std::cout;
using std::cin;
using std::endl;

int main(int argc, char* argv[]) {
	uint16_t frame = 0;
	auto begintime = std::chrono::steady_clock::now();
	float angle = 0;

	std::vector<std::shared_ptr<rst::Triangle>> triangleList;
	
	// test data
	{
		myEigen::Vector3f v[3]{
			myEigen::Vector3f{2,  0, -2},
			myEigen::Vector3f{0,  2, -2},
			myEigen::Vector3f{-2, 0, -2}
		};
		std::shared_ptr<rst::Triangle> t1(new rst::Triangle(v));
		t1->setColor(0, TGAColor(255, 0,   0));
		t1->setColor(1, TGAColor(0,   255, 0));
		t1->setColor(2, TGAColor(0,   0,   255));
		triangleList.push_back(t1);
	}
	{
		myEigen::Vector3f v[3]{
			myEigen::Vector3f{3.5, -1,  -5},
			myEigen::Vector3f{2.5, 1.5, -5},
			myEigen::Vector3f{-1,  0.5, -5}
		};
		std::shared_ptr<rst::Triangle> t1(new rst::Triangle(v));
		t1->setColor(0, TGAColor(255, 0,   0));
		t1->setColor(1, TGAColor(0,   255, 0));
		t1->setColor(2, TGAColor(0,   0,   255));
		triangleList.push_back(t1);
	}

	// ensure the existence of the output directory
	std::string outdirs = "result";
	if (!std::filesystem::exists(outdirs)) {
		std::filesystem::create_directories(outdirs);
	}

	while (true) {
		cout << "frame: " << frame << endl;

		std::string filename = outdirs + "/output" + std::to_string(frame) + ".tga";
		TGAImage image(700, 700, TGAImage::RGB);

		rst::rasterizer rst(filename, image);
		rst.SetCamera(myEigen::Vector3f(0, 0, 5)); // why (0,0,5), not (0,0,0)?
		rst.SetTheta(angle);
		rst.SetRotateAxis(myEigen::Vector3f(1, 1, 0));
		rst.draw(triangleList);
		rst.output();
		frame++;
		angle += 5;
		if (frame > 71) {
			break;
		}
	}

	auto endtime = std::chrono::steady_clock::now();
	cout << "use time: " << std::chrono::duration_cast<std::chrono::duration<double>>(endtime - begintime) << endl;
	return 0;
}
